package com.dirox.jira.notes.action;

import com.atlassian.crowd.embedded.api.User;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.web.action.JiraWebActionSupport;
import com.dirox.jira.notes.entities.Note;
import com.dirox.jira.notes.service.NoteService;
import com.dirox.jira.notes.utils.NoteComparator;
import static com.google.common.base.Preconditions.checkNotNull;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class GetLatestNote extends JiraWebActionSupport {
	private static final long serialVersionUID = 1L;
	private Note latestNote;
	private String issueKey;
	private IssueManager issueManager;
	private NoteService noteService;

	protected String doExecute() throws Exception {
		if (!validateInput()) {
			return ERROR;
		}

		com.dirox.jira.notes.entities.User owner = noteService
			                     .currentUser();
		List<Note> notes = noteService.getNotes(issueKey, owner);
		List<Note> memos = noteService.getMemos(issueKey, owner);
		List<Note> notesAndMemos = new ArrayList<Note>();
		notesAndMemos.addAll(memos);
		notesAndMemos.addAll(notes);

		Collections.sort(notesAndMemos,
		                 new NoteComparator());

		int lastIndex = notesAndMemos.size() - 1;

		if (notesAndMemos.size() > 0) {
			latestNote = notesAndMemos.get(lastIndex);
		}

		return SUCCESS;
	}

	/**
	 * Validate the input parameters
	 *
	 * @return true if validating input success, else return false
	 */
	private boolean validateInput() {
		// check if issue empty or not exist
		if (StringUtils.isBlank(issueKey)
			    || (issueManager.getIssueObject(issueKey) == null)) {
			return false;
		}

		return true;
	}

	public User getCurrentUser() {
		return getLoggedInUser();
	}

	public boolean getIncludeDialog() {
		return true;
	}

	public Note getNote() {
		return latestNote;
	}

	public String getIssueKey() {
		return issueKey;
	}

	public void setIssueKey(String issueKey) {
		this.issueKey = issueKey;
	}

	public void setIssueManager(IssueManager issueManager) {
		this.issueManager = checkNotNull(issueManager);
	}

	public void setNoteService(NoteService noteService) {
		this.noteService = checkNotNull(noteService);
	}
}
